//
//  ViewController.m
//  demo
//
//  Created by mysj on 16/6/27.
//  Copyright © 2016年 MY. All rights reserved.
//

#import "HomeViewController.h"

#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>//引入计算工具所有的头文件

#import <MapKit/MapKit.h>

#import "Masonry.h"
#import "AppConfig.h"
#import "JMenu.h"
#import "CampView.h"
#import "RankView.h"
#import "HomeTopView.h"
#import "HomBottomView.h"
#import "BaseAnimation.h"
#import "DetailsViewController.h"
#import "IMViewController.h"

#import "QuantumWar-Swift.h"

#import "MyAnimatedAnnotationView.h"
#import "JPointAnnotation.h"
#import "UIViewController+Add.h"

//绘制
#import "CustomOverlayView.h"
#import "CustomOverlay.h"

//#import <BaiduMapAPI_Search/BMKSearchComponent.h>
//#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件
//#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入检索功能所有的头文件
//#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>//引入云检索功能所有的头文件
//#import <BaiduMapAPI_Radar/BMKRadarComponent.h>//引入周边雷达功能所有的头文件
//#import <BaiduMapAPI_Map/BMKMapView.h>//只引入所需的单个头文件
//#import "BMKClusterManager.h"
//#import "BMKClusterItem.h"

typedef NS_ENUM(NSInteger, my_camp) {
    k_blue,
    k_green,
};


@interface HomeViewController ()<BMKMapViewDelegate, BMKLocationServiceDelegate> {
    
    my_camp             camp;
    NSInteger           progress;
    
    JPointAnnotation *  an2;
    NSMutableArray  *   array1;
}



/**地图*/
@property (nonatomic, strong) BMKMapView *          mapView;
/**定位*/
@property (nonatomic, strong) BMKLocationService *  locService;
///geo搜索服务BMKGeoCodeSearchDelegate
//@property (nonatomic, strong) BMKGeoCodeSearch *    geocodesearch;
@property (nonatomic, strong) NSMutableArray *        Mpoints;
@property (nonatomic, assign) CLLocationCoordinate2D  selectCoordinate;

@property (nonatomic, strong) JMenu *                 menu;
@property (nonatomic, strong) CampView *              campView;
@property (nonatomic, strong) DetailsViewController * detailsViewController;
@property (nonatomic, strong) IMViewController *      imViewController;
@property (nonatomic, strong) GuideViewController *   guideViewController;
@property (nonatomic, strong) StrongholdViewController *strongholdViewController;
@property (nonatomic, strong) NSMutableArray *        imgMarray;
@property (nonatomic, strong) BaseAnimation *         baseAnimation;
@property (nonatomic, strong) BubbleTransitionAnimation *bubbleTransitionAnimation;
@property (nonatomic, strong) HomeTopView *           topView;
@property (nonatomic, strong) HomBottomView *         bottomView;

@end


@implementation HomeViewController

#pragma mark -
//
- (void)loadView {
    [super loadView];
    [self prepareSubviews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _locService.delegate = self;
    _mapView.delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
    
    _mapView.delegate = nil;
    _locService.delegate = nil;
    
//        _geocodesearch.delegate = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
// 开始定位
//        [self startLocating];
    self.view.backgroundColor = [UIColor whiteColor];
//    [self onClickGeocode];
//    camp = k_green;
    
    return;
    /**
     *计算指定两点之间的距离
     *@param a 第一个坐标点
     *@param b 第二个坐标点
     *@return 两点之间的距离，单位：米
     */
//    CLLocationDistance mag = BMKMetersBetweenMapPoints(temppoints2[0], temppoints2[1]);
//    NSLog(@"%f   距离", mag);
    
    
//    
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        
//        array1  = [NSMutableArray arrayWithCapacity:1000];
//        
//        for (int i = 0; i < 1000; i++) {
//            
//            CLLocationCoordinate2D coor;
//            double lat =  (arc4random() % 100) * 0.05f;
//            double lon =  (arc4random() % 100) * 0.03f;
//            coor.latitude = 38 + lat;
//            coor.longitude = 116 + lon;
//            
//            BMKPointAnnotation *  animatedAnnotation = [[BMKPointAnnotation alloc]init];
//            animatedAnnotation.coordinate = coor;
//            
//            [array1 addObject:animatedAnnotation];
//        }
//        
//        dispatch_sync(dispatch_get_main_queue(), ^{
//            
//            [self.mapView addAnnotations:array1];
//            [self.mapView mapForceRefresh];
//        });
//        
//    });
//    
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        
//        NSMutableArray *array = [NSMutableArray arrayWithCapacity:100];
//        
//        for (int i = 0; i < 300; i++) {
//            
//            CLLocationCoordinate2D coor;
//            
//            double lat =  arc4random() % 39 + 19.0034f;
//            double lon =  arc4random() % 116 + 80.330f;
//            //            NSLog(@"%f %f", lat , lon);
//            coor.latitude =  lat;
//            coor.longitude = lon;
//            
//            an2 = [[JPointAnnotation alloc] init];
//            an2.coordinate = coor;
//            
//            [array addObject:an2];
//        }
//        
//        dispatch_sync(dispatch_get_main_queue(), ^{
//            
//            [self.mapView addAnnotations:array];
//            [self.mapView mapForceRefresh];
//        });
//        
//    });
}

- (void)dealloc {
    
    if (_locService) {
        _locService = nil;
    }
    if (_mapView) {
        _mapView = nil;
    }
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (self.guideViewController == nil) {
        self.guideViewController = [[GuideViewController alloc] init];
    }
    
    self.view.backgroundColor = [UIColor blueColor];
//     CGPoint loc = [touches.anyObject locationInView:self.view];
    
 
    
    if (!self.bubbleTransitionAnimation) {
        _bubbleTransitionAnimation = [[BubbleTransitionAnimation alloc] init];
    }
//    self.bubbleTransitionAnimation.startPoint = loc;
//    self.bubbleTransitionAnimation.duration = 1;
//    self.guideViewController.transitioningDelegate = self.bubbleTransitionAnimation;
//    self.guideViewController.modalPresentationStyle = UIModalPresentationCustom;
//    [self.navigationController presentViewController:self.guideViewController animated:YES completion:nil];
    
//    self.navigationController.navigationBar.hidden = YES;
//    self.guideViewController.transitioningDelegate = self.baseAnimation;
//    self.guideViewController.modalPresentationStyle = UIModalPresentationCustom;
//    [self.navigationController presentViewController:self.guideViewController animated:YES completion:nil];
    
//    //    [self.view addSubview:im.view];
}

#pragma mark- API
//通信按钮
- (void) correspondedBtnClick:(UIButton *)sender {
    
    self.navigationController.navigationBar.hidden = YES;
    self.imViewController.transitioningDelegate = self.baseAnimation;
    self.baseAnimation.sizetype = kSizeTypeBp;
    self.imViewController.modalPresentationStyle = UIModalPresentationCustom;
    [self.navigationController presentViewController:self.imViewController animated:YES completion:nil];
}

- (void)onClickGeocode {
    
    self.detailsViewController.transitioningDelegate = self.baseAnimation;
    self.detailsViewController.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:self.detailsViewController animated:YES completion:nil];

    [self.view addSubview:self.detailsViewController.view];

    
}


//申请据点
- (void)getStronghold {
    if (!self.strongholdViewController) {
        self.strongholdViewController = [[StrongholdViewController alloc] init];
    }
    
    [self presentViewController:self.strongholdViewController animated:YES completion:nil];
    
}

//添加聚点
- (void)createFocalpoint {
    
    BMKPointAnnotation * an = [[BMKPointAnnotation alloc] init];
    an.coordinate = self.selectCoordinate;
    
    [_mapView addAnnotation:an];
    [_mapView mapForceRefresh];
    
}
// 连接聚点
- (void)connectFocalpoint {
    
    BMKMapPoint pt;
    BMKMapPoint * temppoints = new BMKMapPoint[3];
    for (int i = 0; i < self.Mpoints.count; i++) {
        [self.Mpoints[i] getValue:&pt];
        temppoints[i].y = pt.y;
        temppoints[i].x = pt.x;
        CLLocationDistance mag = BMKMetersBetweenMapPoints(temppoints[i], temppoints[i + 1]);
        NSLog(@"%f  距离", mag);
    }
    
    
    CustomOverlay* custom2 = [[CustomOverlay alloc] initWithPoints:temppoints count:3];
    [_mapView addOverlay:custom2];
    [_mapView mapForceRefresh];
    [self.Mpoints removeAllObjects];
}

- (void)customLocationAccuracyCircle {
    
    BMKLocationViewDisplayParam *param = [[BMKLocationViewDisplayParam alloc] init];
    param.accuracyCircleStrokeColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:1.0];
    param.accuracyCircleFillColor = [UIColor colorWithRed:0 green:1 blue:0 alpha:1.0];
    [_mapView updateLocationViewWithParam:param];
}


#pragma mark - BMKMapViewDelegate
/**
 *点中底图空白处会回调此接口
 *@param mapview 地图View
 *@param coordinate 空白处坐标点的经纬度
 */
- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate {
    
    self.selectCoordinate = coordinate;
    
    BMKMapPoint pt = BMKMapPointForCoordinate(coordinate);
    NSValue *value = [NSValue valueWithBytes:&pt objCType:@encode(BMKMapPoint)];
    [self.Mpoints addObject:value];
 
    if (self.Mpoints.count >= 3) {
        [self connectFocalpoint];
    }
    
    [self.menu buttonClick];
    
}
// 双击地图时会回调此接口
- (void)mapview:(BMKMapView *)mapView onDoubleClick:(CLLocationCoordinate2D)coordinate {
    
    NSLog(@"维度%f  精度%f", coordinate.latitude, coordinate.longitude);
}

//地图长按事件
-(void)mapview:(BMKMapView *)mapView onLongClick:(CLLocationCoordinate2D)coordinate {
    
    NSLog(@"维度%f  精度%f", coordinate.latitude, coordinate.longitude);
    
}


// 根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation {
    
    if ([annotation class] == [JPointAnnotation class]) {
        
        NSString *anID = @"dianId";
        BMKAnnotationView *an = nil;
        if (an == nil) {
            an = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:anID];
        }
        an.image = [UIImage imageNamed:@"dian"];
        return an;
    }
    
    NSString *AnnotationViewID = @"AnimatedAnnotation";
    MyAnimatedAnnotationView *annotationView = nil;
    if (annotationView == nil) {
        annotationView = [[MyAnimatedAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
    }
    annotationView.annotationImages = self.imgMarray;
    annotationView.iconImgView.image = [self getImageFromView:self.campView];
    
    return annotationView;
}

/**
 *根据overlay生成对应的View
 *@param mapView 地图View
 *@param overlay 指定的overlay
 *@return 生成的覆盖物View
 */
- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id <BMKOverlay>)overlay {
    
    if ([overlay isKindOfClass:[CustomOverlay class]]) {
        
        CustomOverlayView* cutomView = [[CustomOverlayView alloc] initWithOverlay:overlay];
        
        UIColor *stokeColor = RGBA(36, 221, 227, 1.0);
        UIColor *fillColor  = RGBA(36, 221, 227, 0.3);
        if (camp == k_green) {
            stokeColor = RGBA(41, 255.0, 6, 1.0);
            fillColor  = RGBA(41, 255.0, 6, 0.3);
        }
        
        cutomView.strokeColor = stokeColor;
        cutomView.fillColor = fillColor;
        cutomView.lineDash = YES;
        cutomView.lineWidth = 1.0;
        return cutomView;
    }
    return nil;
}

/**
 *当点击annotation view弹出的泡泡时，调用此接口
 *@param view 泡泡所属的annotation view
 */
- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view {
    
    NSLog(@"点击了");
}


/**
 *地图初始化完毕时会调用此接口
 */
- (void)mapViewDidFinishLoading:(BMKMapView *)mapView {
    
    NSLog(@"初始化完毕");
    
}

/**
 *地图渲染每一帧画面过程中，以及每次需要重绘地图时（例如添加覆盖物）都会调用此接口
 *@param status 此时地图的状态
 */
- (void)mapView:(BMKMapView *)mapView onDrawMapFrame:(BMKMapStatus *)status {
    if (mapView.zoomLevel >=16.0f) {
        
//        NSLog(@"缩放");
        return;
    } else if (mapView.zoomLevel <=10.0f) {
        
        [mapView removeAnnotations:array1];
        [mapView mapForceRefresh];
    }
    NSLog(@"%f", mapView.zoomLevel);
}



#pragma mark- 定位
- (void)startLocating {
    
    NSLog(@"进入普通定位态");
    [self.locService startUserLocationService];
    _mapView.showsUserLocation = NO;//先关闭显示的定位图层
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;//设置定位的状态
    _mapView.showsUserLocation = YES;//显示定位图层
}

- (void)endLocating {
    
    [_locService stopUserLocationService];
    _mapView.showsUserLocation = NO;
}

/**
 *在地图View将要启动定位时，会调用此函数
 */
- (void)willStartLocatingUser {
    
    NSLog(@"start locate");
}
/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
    
    //    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    NSLog(@"用户位置更新后");
    [_mapView updateLocationData:userLocation];
    
}

/**
 *在地图View停止定位后，会调用此函数
 */
- (void)didStopLocatingUser {
    
    NSLog(@"定位停止");
}

/**
 *定位失败后，会调用此函数
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error {
    
    NSLog(@"定位 error");
    
}



#pragma mark- 控件

- (void)prepareSubviews {
    self.navigationController.navigationBar.hidden = YES;
    
    [self.view addSubview:self.mapView];
    [self.view addSubview:self.menu];
    [self.view addSubview:self.topView];
    [self.view addSubview:self.bottomView];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.equalTo(@37);
    }];
    
    [self.menu mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.bottomView.mas_top).offset(-5);
        make.left.equalTo(self.view.mas_left).offset(5);
    }];
    
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(10);
        make.left.right.equalTo(self.view);
        make.height.equalTo(@58);
    }];
}


#pragma mark -
- (NSMutableArray *)imgMarray {
    
    if (_imgMarray == nil) {
        _imgMarray = [NSMutableArray arrayWithCapacity:6];
        for (int i = 0; i < 6; i++) {
            UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"camp_seletct_%d",i]];
            [_imgMarray addObject:img];
        }
    }
    return _imgMarray;
}

- (BaseAnimation *)baseAnimation {
    if (!_baseAnimation) {
        _baseAnimation = [BaseAnimation new];
    }
    return _baseAnimation;
}

- (IMViewController *)imViewController {
    if (_imViewController == nil) {
        _imViewController = [[IMViewController alloc] init];
    }
    return _imViewController;
}

- (DetailsViewController *)detailsViewController {
    if (_detailsViewController == nil) {
        _detailsViewController = [[DetailsViewController alloc] init];
    }
    return _detailsViewController;
}

- (NSMutableArray *)Mpoints {
    
    if (_Mpoints == nil) {
        _Mpoints = [NSMutableArray arrayWithCapacity:3];
    }
    return _Mpoints;
}

- (CampView *)campView {
    
    if (_campView == nil) {
        _campView = [CampView camp];
        _campView.rbCamp = YES;
        [self.view addSubview:_campView];
    }
    return _campView;
}

- (JMenu *)menu {
    
    if (_menu == nil) {
       __block typeof(self)bself = self;
        _menu = [JMenu menuImg:@[@"pilotBtn_0",@"pilotBtn_1", @"pilotBtn_2"] Selected:^(NSInteger indx) {
            if (indx == 2) {
                [bself createFocalpoint];
            } else {
                [bself getStronghold];
            }
        }];
        
    }
    return _menu;
}

- (HomBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[HomBottomView alloc] init];
        [_bottomView setImageNames:@[@"bototmView_bj_0", @"bototmView_bj_1" ,@"corresponded_0"]];
        [_bottomView.correspondedBtn addTarget:self action:@selector(correspondedBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bottomView;
}

- (HomeTopView *)topView {
    
    if (_topView == nil) {
        _topView = [[HomeTopView alloc] init];
    }
    return _topView;
}

- (BMKLocationService *)locService {
    
    if (_locService == nil) {
        _locService = [[BMKLocationService alloc] init];
        _locService.delegate = self;
    }
    return _locService;
}

- (BMKMapView *)mapView {
    
    if (_mapView == nil) {
        //黑夜 午夜蓝
        NSString* path = [[NSBundle mainBundle] pathForResource:@"custom_config_午夜蓝" ofType:@""];
        [BMKMapView customMapStyle:path];
        
        _mapView = [[BMKMapView alloc] initWithFrame:self.view.bounds];
        _mapView.showMapPoi = NO;
        _mapView.overlookEnabled = NO;
        _mapView.zoomEnabledWithTap = NO;  //双击
        _mapView.buildingsEnabled = NO;     //3D楼的效果
        _mapView.trafficEnabled = NO;
        //        _mapView.zoomEnabled = NO;
        //        _mapView.showsUserLocation = YES;
        _mapView.mapType = BMKMapTypeStandard;
        _mapView.trafficEnabled = NO;//关闭实时路况图层
        _mapView.zoomLevel = 16;
        
    }
    return _mapView;
}

@end
